/*
 * dhcp.c
 *
 *  Created on: 2018-3-13
 *      Author: Iron
 */

#include "contiki-net.h"
#include "net/ip/dhcpc.h"

PROCESS(dhcpc_process, "DHCP");
AUTOSTART_PROCESSES(&dhcpc_process);

/*---------------------------------------------------------------------------*/
ICACHE_FLASH_ATTR
PROCESS_THREAD(dhcpc_process, ev, data)
{
  PROCESS_BEGIN();

  dhcpc_init(uip_lladdr.addr, sizeof(uip_lladdr.addr));

  os_printf("Requesting DHCP configuration...\n");
  dhcpc_request();

  while(1) {
    PROCESS_WAIT_EVENT();

    if(ev == tcpip_event || ev == PROCESS_EVENT_TIMER) {
      dhcpc_appcall(ev, data);
    } else if(ev == PROCESS_EVENT_EXIT) {
      process_exit(&dhcpc_process);
    }
  }

  PROCESS_END();
}
/*---------------------------------------------------------------------------*/
void ICACHE_FLASH_ATTR
dhcpc_configured(const struct dhcpc_state *s)
{
	uip_sethostaddr(&s->ipaddr);
	uip_setnetmask(&s->netmask);
	uip_setdraddr(&s->default_router);
	uip_nameserver_update(&s->dnsaddr, UIP_NAMESERVER_INFINITE_LIFETIME);

	os_printf("dhcpc_configured:\n");
	os_printf("Got IP address %d.%d.%d.%d\n", uip_ipaddr_to_quad(&s->ipaddr));
	os_printf("Got netmask %d.%d.%d.%d\n",	 uip_ipaddr_to_quad(&s->netmask));
	os_printf("Got DNS server %d.%d.%d.%d\n", uip_ipaddr_to_quad(&s->dnsaddr));
	os_printf("Got default router %d.%d.%d.%d\n", uip_ipaddr_to_quad(&s->default_router));
	os_printf("Lease expires in %ld seconds\n", uip_ntohs(s->lease_time[0])*65536ul + uip_ntohs(s->lease_time[1]));
}

/*---------------------------------------------------------------------------*/
void ICACHE_FLASH_ATTR
dhcpc_unconfigured(const struct dhcpc_state *s)
{
	os_printf("dhcpc request fail:\n");
	os_printf("Got IP address %d.%d.%d.%d\n", uip_ipaddr_to_quad(&s->ipaddr));
	os_printf("Got netmask %d.%d.%d.%d\n",	 uip_ipaddr_to_quad(&s->netmask));
	os_printf("Got DNS server %d.%d.%d.%d\n", uip_ipaddr_to_quad(&s->dnsaddr));
	os_printf("Got default router %d.%d.%d.%d\n", uip_ipaddr_to_quad(&s->default_router));
	os_printf("Lease expires in %ld seconds\n", uip_ntohs(s->lease_time[0])*65536ul + uip_ntohs(s->lease_time[1]));
}

/*---------------------------------------------------------------------------*/
void ICACHE_FLASH_ATTR
dhcpc_process_init(void)
{
#if !(AUTOSTART_ENABLE)
	process_start(&dhcpc_process, NULL);
#endif
}
